package com.jf.yytgd.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf.yytgd.converter.TokenConverter;
import com.jf.yytgd.dao.TokenMapper;
import com.jf.yytgd.entity.bean.Token;
import com.jf.yytgd.entity.dto.token.TokenDTO;
import com.jf.yytgd.service.TokenService;
import com.jf.yytgd.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2025-02-24
 * Time:10:42
 */
@Transactional(isolation = Isolation.READ_COMMITTED)
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, Token> implements TokenService {
    @Resource
    private TokenMapper tokenMapper;

    @Override
    public boolean verify(String token) {
        Map<String, Object> payload = JwtUtil.getPayload(token);
        if (payload != null) {
            Integer userId = (Integer) payload.get("userId");
            String dbToken = tokenMapper.selectByUserId(userId);
            return dbToken != null && dbToken.equals(token);
        }
        return false;
    }

    @Override
    public void update(String token) {
        Map<String, Object> payload = JwtUtil.getPayload(token);
        UpdateWrapper<Token> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id", payload.get("userId"));
        wrapper.set("token", token);
        tokenMapper.update(wrapper);
    }
    @Override
    public void save(TokenDTO tokenDTO) {
        tokenMapper.insert(TokenConverter.INSTANCE.toBean(tokenDTO));
    }
}
